% (1+1)-ES with 1/5 rule Slide 76
% Michael Sieber / Philipp Rusch

%initialization (line 1)
randn("state", 7);
N = 10;
parent = 10 * ones(N, 1); % all vector values are 10
sigma = 1.0;
sigmaStop = 10^-5;

% 1/5 Rule adaptions
pOpt = 0.2;
alpha = 1.2;
G = N;

% determine initial parent fitness (line 2)
parent_fitness = F(parent);

% generation counter (line 3)
g = 0;

% generation and fitness log for plotting
plot_generations(g+1) = [g];
plot_fitness(g+1) = [parent_fitness];

% evolution loop (line 4)
while(sigma > sigmaStop)
	% count successfull mutations in G
	ns = 0;
	
	% mutation loop with constant sigma
	for k=1:G
		% calculate offsprings (line 5-6)
		offspring = parent + sigma * randn(N, 1);
		offspring_fitness = F(offspring);
	
		% minimization (line 7-10)
		if(offspring_fitness <= parent_fitness)
			parent = offspring;
			parent_fitness = offspring_fitness;
			ns = ns + 1; % successful mutation counter
		endif
	
		% generation increase (line 11)
		g = g+1;
		
		% add the plot values
		plot_generations(g) = [g];
		plot_fitness(g) = [parent_fitness];
	endfor
	
	ps = ns / G;
	if(ps > pOpt)
		sigma = sigma * alpha;
	elseif(ps < pOpt)
		sigma = sigma / alpha;
	endif
endwhile

% print the result
clf();
ex2a(); % print result from 2a
hold on
semilogy(plot_generations, plot_fitness);
ylabel("Parental Fitness F(y)");
xlabel("Generations");
axis([0, 2000, 0.1, 1000]); %[xmin, xmax, ymin, ymax]
